from cou.api_1_0 import api
from cou.models import Area,Taocan
from flask import jsonify,current_app,request
from cou.utils.response_code import RET
from cou import redis_store
from cou.utils.constants import AREA_INFO_TIME_OUT
import json
@api.route("/areas")
def get_area():
    try:
        area_return=redis_store.get('area_info').decode()
    except Exception as e:
        current_app.logger.error(e)
    if not area_return:
        try:
            area=Area.query.all()
            area_return=[i.to_dict() for i in area]
            redis_store.setex('area_info',AREA_INFO_TIME_OUT,json.dumps(area_return))
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="数据库错误")
    else:
        area_return=json.loads(area_return)
    return jsonify(errno=RET.OK,errmsg="成功",data=area_return)

@api.route("/taocans/index")
def get_index():
    try:
        taocan_return=redis_store.get('home_page').decode()
    except Exception as e:
        current_app.logger.error(e)
    if not taocan_return:
        try:
            taocans=Taocan.query.order_by(Taocan.price).limit(5).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="数据库错误")
        taocan_return=[i.to_index() for i in taocans]
        redis_store.setex('home_page',AREA_INFO_TIME_OUT,json.dumps(taocan_return))
    else:
        taocan_return=json.loads(taocan_return)
    
    return jsonify(errno=RET.OK,errmsg="成功",data=taocan_return)



